package com.xin.data.simbapesa.api;

import android.util.Log;

import androidx.annotation.NonNull;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import io.reactivex.rxjava3.core.Observable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RxHttp {

    public static Observable<String> get(String url) {
        return Observable.create(emitter -> {
            OkHttpClient client = HttpClient.getClient();
            Request request = new Request.Builder().url(url).build();

            try (Response response = client.newCall(request).execute()) {
                if (!emitter.isDisposed()) {
                    if (response.isSuccessful()) {
                        String data = response.body().string();
                        emitter.onNext(data);
                        emitter.onComplete();
                    } else {
                        emitter.onError(new IOException("Request failed: " + response.code()));
                    }
                }
            } catch (Exception e) {
                if (!emitter.isDisposed()) {
                    emitter.onError(e);
                }
            }
        });
    }

    public static Observable<String> uploadImage(String url, File file) {
        return Observable.create(emitter -> {

            OkHttpClient client = HttpClient.getClient();

            MediaType mediaType=MediaType.Companion.parse("image/*");
            RequestBody fileBody=RequestBody.Companion.create(file,mediaType);
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("image", file.getName(),fileBody)
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();

            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    if (!emitter.isDisposed()) {
                        emitter.onError(e);
                    }
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    if (response.isSuccessful() && response.body() != null) {
                        String result = response.body().string();
                        if (!emitter.isDisposed()) {
                            emitter.onNext(result);
                            emitter.onComplete();
                        }
                    } else {
                        if (!emitter.isDisposed()) {
                            emitter.onError(new IOException("Upload failed: " + response.code()));
                        }
                    }
                }
            });
            emitter.setCancellable(call::cancel);
        });
    }

    public static Observable<String> post(String url, String jsonBody, HashMap<String, String> headers) {
        return Observable.create(emitter -> {
            OkHttpClient client = HttpClient.getClient();
            RequestBody body = RequestBody.create(jsonBody, MediaType.parse("text/plain"));
            Request.Builder mBuilder = new Request.Builder();
            if (headers != null && !headers.isEmpty()) {
                for (String key : headers.keySet()) {
                    String value = headers.get(key);
                    if (key != null && value != null) {
                        mBuilder.addHeader(key, value);
                    }
                }
            }
            Request request = mBuilder
                    .url(url)
                    .post(body)
                    .build();

            Log.e("me","url->"+url);

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    if (!emitter.isDisposed()) {
                        emitter.onError(e);
                    }
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    try {
                        if (response.isSuccessful()) {
                            assert response.body() != null;
                            String data = response.body().string();
                            emitter.onNext(data);
                            emitter.onComplete();
                        } else {
                            emitter.onError(new IOException("Request failed: " + response.code()));
                        }
                    } catch (IOException e) {
                        emitter.onError(e);
                    }
                }
            });
        });
    }

}
